package com.laoye.Intercepter;
import com.laoye.Exception.exception.BaseException;

import com.laoye.util.JwtUtil;
import com.laoye.util.ThreadLocal;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;


@Component
public class JwtInterceptor implements HandlerInterceptor {
    private final JwtUtil jwtUtil;
    private final StringRedisTemplate stringRedisTemplate;


    public JwtInterceptor(JwtUtil jwtUtil, StringRedisTemplate stringRedisTemplate) {
        this.jwtUtil = jwtUtil;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 获取请求头中令牌
        String token = request.getHeader("Authorization");
        if(token==null|| token.isEmpty()){
            throw new BaseException(401,"令牌不能为空");
        }
        if (!token.startsWith("Bearer ")){
            throw new BaseException(401,"令牌格式有误");
        }
        token=token.substring(7);
        if (!jwtUtil.validateToken(token)){
            throw new BaseException(401,"令牌无效或已过期" );
        }
        // 从令牌中获取用户ID
        Integer id = jwtUtil.getClaim(token, claims -> claims.get("id", Integer.class));
        // 从令牌中获取用户名
        String username= jwtUtil.getClaim(token, claims -> claims.get("username", String.class));
        //获取角色
        String role=jwtUtil.getClaim(token, claims -> claims.get("role", String.class));
        // 从Redis中获取令牌

        String redisToken = role.equals("admin")?stringRedisTemplate.opsForValue().get("AdminJWTToken" +id+":"):
                stringRedisTemplate.opsForValue().get("UserJWTToken" +id+":" );
        // 判断令牌是否一致
        if (redisToken != null && !redisToken.equals(token)) {
            throw new BaseException(401, "令牌失效，请重新登录");
        }
        // 将用户ID保存到ThreadLocal中
        ThreadLocal.setCurrentId(id);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  {
            ThreadLocal.removeCurrentId();

    }
}
